package encrypt

import (
	"crypto/aes"
	"encoding/base64"
)

func EncryptAESByECB(origData []byte, key []byte) (*string, error) {
	// 分组秘钥
	// NewCipher该函数限制了输入k的长度必须为16, 24或者32
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()               // 获取秘钥块的长度
	origData = pkcs5Padding(origData, blockSize) // 补全码
	encrypted := make([]byte, len(origData))     // 创建数组
	for bs, be := 0, blockSize; bs < len(origData); bs, be = bs+blockSize, be+blockSize {
		block.Encrypt(encrypted[bs:be], origData[bs:be])
	}

	encoded := base64.RawURLEncoding.EncodeToString(encrypted)
	return &encoded, nil
}

func DecryptAESByECB(encrypted []byte, key []byte) (*string, error) {
	cryted := string(encrypted)
	encryptedByte, err := base64.RawURLEncoding.DecodeString(cryted)
	if err != nil {
		return nil, err
	}

	block, err := aes.NewCipher(key) // 分组秘钥
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize() // 获取秘钥块的长度
	encryptedByte = pkcs5Padding(encrypted, blockSize)
	decrypted := make([]byte, len(encryptedByte)) // 创建数组
	for bs, be := 0, blockSize; bs < len(encryptedByte); bs, be = bs+blockSize, be+blockSize {
		block.Decrypt(decrypted[bs:be], encryptedByte[bs:be])
	}
	decryptedText := string(decrypted)
	return &decryptedText, nil
}
